<template>
	<el-drawer
	  v-model="drawer.visible"
	  :title="drawer.title"
	  append-to-body
	  size="650"
	  @close="closeDialog"
	  :close-on-click-modal="false"
	>
		<div class="api-debugger-pane">
			<div class="section-title">
			  <span class="title-form_primary">请求地址</span>
			</div>
			<div class="url-bar">
				<el-input
				  v-model="url"
				  placeholder=""
				  class="input-with-select"
				  readonly
				>
				  <template #prepend>
					<el-select v-model="requestMethod" placeholder="请选择请求方法" style="width: 105px">
					  <el-option label="GET" value="GET" />
					  <el-option label="POST" value="POST" />
					</el-select>
				  </template>
				  <template #append>
					<el-button icon="Right" @click="handleSubmit" :loading="loading" />
				  </template>
				</el-input>
			</div>
			<el-scrollbar height="calc(100% - 100px)">
				<div style="display: flex;flex-direction: column;">
					<div style="flex: 0.5; padding-bottom: 5px;">
						<div class="section-title">
						  <span class="title-form_primary">请求参数</span>
						</div>
						<el-tabs v-model="activeTab" style="height:calc(100% - 50px);">
							<el-tab-pane label="参数" name="params" style="height: 100%;">
								<div class="well">
									<el-scrollbar height="100%" >
										<el-form ref="reqArgumentsFormRef" :model="formData" :rules="rules" label-width="100px">
											<el-form-item :label="item.name" :prop="item.identifier" v-for="(item, index) in pageData" :key="index">
												<el-input v-model="formData[item.identifier]" :placeholder="item.name" />
											</el-form-item>
										</el-form>
									</el-scrollbar>
								</div>
							</el-tab-pane>
							<el-tab-pane label="TypeScript" name="typescript" style="height: 100%;">
								<el-scrollbar height="400">
									<div class="baseMirror">
										<MonacoEditor
											v-model="code"
											language="typescript"
											:options="{
												readOnly: true,
												minimap: { enabled: false }
											}"
										/>
									</div>
								</el-scrollbar>
							</el-tab-pane>
						</el-tabs>
					</div>
					
					<div style="flex: 0.5; ">
						<div class="section-title">
						  <span class="title-form_primary">请求结果</span>
						</div>
						<div class="json-output">
							<el-scrollbar height="100%" >
								<vue-json-pretty :data="responseData" />
							</el-scrollbar>
						</div>
					</div>
				</div>
			</el-scrollbar>
		</div>		
	</el-drawer>
</template>

<script lang="ts" setup>
	import { ref, reactive } from "vue";
	import { onMounted } from "vue";
	import DbapiAPI from "@/api/biz/dbapi";
	import { ElForm } from "element-plus";
	import VueJsonPretty from 'vue-json-pretty';
	import 'vue-json-pretty/lib/styles.css';
	import MonacoEditor from '@/components/MonacoEditor/index.vue'

	const loading = ref<boolean>(false);
	const dialog = ref({
		visible:false,
		title:'',
	});
	
	const drawer = ref({
		visible:false,
		title:'',
	});
	const apiData=ref<any>();
	const url=ref<string>("/api/")
	const requestMethod=ref<string>("POST");
	const pageData = ref<any[]>([]);
	const reqArgumentsFormRef = ref(ElForm);
	const formData = reactive<any>({
	});
	const responseData = ref<any>(null);
	const activeTab = ref<string>('params');
	const code = ref();


	// 为 rules 定义一个显式类型
	const rules = reactive<{ [key: string]: Array<{ required: boolean, message: string, trigger: string }> }>({});
	
	// 查询
	function handleQuery() {
	  loading.value = true;
	  DbapiAPI.geReqArguments({apiId:apiData.value?.id})
	    .then((data:any) => {
			for(var row of data){
				if(row.params){
					for(var param of row.params){
						if(param.required=='1'){
							rules[param.fieldIdentifier] = [{ required: true, message: ""+param.fieldName+"必填. ", trigger: "blur" }];  
						}
						formData[param.fieldIdentifier]=undefined;
						pageData.value.push(param)
					}
				}
			}
			code.value = generateTsClass();
	    })
	    .finally(() => {
	      loading.value = false;
	    });
	}
	
	// 重置查询
	function handleResetQuery() {
	  handleQuery();
	}

	// 生成 TypeScript 类
	function generateTsClass() {
		let classDefinition = `
			interface ApiData {
		`;
		pageData.value.forEach((item: any) => {
		  const fieldName = item.identifier;
		  const fieldType = mapFieldType(item.type);
		  const comment = item.name;
		  classDefinition += `  /** ${comment} */\n  ${fieldName}: ${fieldType};\n\n`;
		});
		classDefinition += `}`;
		return classDefinition;
	}

	// 映射 fieldType 到 TypeScript 类型
	function mapFieldType(fieldType: string): string {
		switch (fieldType?.toLowerCase()) {
		  case 'float':
		  case 'double':
		  case 'int':
		  case 'long':
		  case 'short':
			return 'number';
		  case 'string':
		  case 'char':
			return 'string';
		  case 'boolean':
			return 'boolean';
		  case 'date':
		  case 'datetime':
			return 'Date';
		  case 'byte':
			return 'number';
		  default:
			return 'any';
		}
	}

	async function openDialog(row?: any) {
		drawer.value.visible=true;
		drawer.value.title="接口【"+row.name+'】调试';
		apiData.value=row;
		url.value="/api"+row.uri
		handleResetQuery();
	}
	
	const emits = defineEmits(['closeDialog'])
	const closeDialog=()=>{
		drawer.value.visible=false;
		drawer.value.title="";
		apiData.value="";
		apiData.value={};
		
		dialog.value.visible = false;
		reqArgumentsFormRef.value.resetFields();
		reqArgumentsFormRef.value.clearValidate();
		pageData.value=[];
	}
	
	function handleSubmit() {
		reqArgumentsFormRef.value.validate((valid: boolean) => {
			if (valid) {
			  loading.value = true;
			  DbapiAPI.sendPost(url.value,formData)
			    .then((data:any) => {
					ElMessage.success("成功");
					responseData.value={
						code:200,
						msg:"成功.",
						data:data
					}
			    })
			    .finally(() => (loading.value = false));
			}
		});
	}
	
	defineExpose({
	  openDialog,closeDialog
	});
	onMounted(() => {
	});
</script>

<style scoped>
	
	:deep(.el-drawer__body){
		width: 18px !important;
		height: 18px !important;;
		background-color: #d5d5d5;
	}

	.section-title {
		font-size: 14px;
		font-weight: 600;
		margin-bottom: 8px;
		color: #555;
		border-bottom: 1px solid #cccccc4f;
		padding-bottom: 4px;
		height: 40px;
		line-height: 40px;
		padding-left: 5px;
	}

	.url-bar {
		border-radius: 4px;
		height: 40px;
	}
	.cm-s-monokai {
	  background-color: #272822 !important;
	  color: #f8f8f2 !important;
	}
	.api-debugger-pane{
		height: calc(100%);
		width: 100%;
		overflow: hidden;
	}
	
	.well {
		padding: 12px;
		height: 100%;
		border: 1px solid #cccccc4f;
	}
	
	.baseMirror{
		border: 1px solid #cccccc4f;
		position: absolute;
		width: 100%;
		height: 100%;
	}
	
	.json-output {
		padding: 12px;
		height: calc(100% - 50px);
		border: 1px solid #cccccc4f;
	}
</style>